package com.bienvenue.main.ui.activity.enterprise;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.bienvenue.main.R;
import com.bienvenue.main.base.BaseActivity;
import com.bienvenue.main.httpService.ResponseObserver;
import com.bienvenue.main.model.HttpBean;
import com.bienvenue.main.serviceApi.ServiceModel;
import com.bienvenue.main.ui.activity.enterprise.EnterpriseMainActivity;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @ProjectName: Bienvenue
 * @Package: com.bienvenue.main.ui.activity
 * @ClassName: BusinessLicenseCertificationActivity
 * @Description: 营业执照认证
 * @Author: Mr.Chen
 * @CreateDate: 2020/9/10 9:15
 * @UpdateUser: Mr.Chen
 * @UpdateDate: 2020/9/10 9:15
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */


public class BusinessLicenseCertificationActivity extends BaseActivity {

    @BindView(R.id.iv_business_license)
    ImageView ivBusinessLicense;
    @BindView(R.id.tv_send_business_license)
    TextView tvSendBusinessLicense;
    @BindView(R.id.et_prompt_name)
    EditText etPromptName;

    String phone;
    String pwd;
    String superCode;
    String commpanyName;
    String url;
    File file;

    MaterialDialog dialog;
    private static int REQUEST_PERMISSIONS = 1;

    @Override
    protected void initData() {

    }

    @Override
    protected void initView() {
        initPermission();

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            phone = bundle.getString("phone");
            pwd = bundle.getString("pwd");
            superCode = bundle.getString("superCode");
            commpanyName = bundle.getString("enterpriseName");

        }
        dialog = initDialog("请稍后...");

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_business_license_certification;
    }

    @OnClick(R.id.iv_return_btn)
    void onFinish() {
        this.finish();
    }

    @OnClick(R.id.tv_send_business_license)
    void onSendBusinessPhoto() {
        //参数很多，根据需要添加
        PictureSelector.create(BusinessLicenseCertificationActivity.this)
                .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .maxSelectNum(1)// 最大图片选择数量
                .minSelectNum(1)// 最小选择数量
                .imageSpanCount(4)// 每行显示个数
                .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选PictureConfig.MULTIPLE : PictureConfig.SINGLE
                .previewImage(true)// 是否可预览图片
                .isCamera(true)// 是否显示拍照按钮
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                //.setOutputCameraPath("/CustomPath")// 自定义拍照保存路径
                .enableCrop(true)// 是否裁剪
                .compress(true)// 是否压缩
                //.sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                .withAspectRatio(1, 1)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                //.selectionMedia(selectList)// 是否传入已选图片
                //.previewEggs(false)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
                //.cropCompressQuality(90)// 裁剪压缩质量 默认100
                //.compressMaxKB()//压缩最大值kb compressGrade()为Luban.CUSTOM_GEAR有效
                //.compressWH() // 压缩宽高比 compressGrade()为Luban.CUSTOM_GEAR有效
                //.cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效
                .rotateEnabled(false) // 裁剪是否可旋转图片
                //.scaleEnabled()// 裁剪是否可放大缩小图片
                //.recordVideoSecond()//录制视频秒数 默认60s
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }

    @OnClick(R.id.tv_send_btn)
    void onSend() {
        if (url == null || TextUtils.isEmpty(url)) {
            showToast("请先上传营业执照");
            return;
        }
        dialog.show();
        ServiceModel.getServiceModel().onEnterpriseRegister(etPromptName.getText().toString().trim(), phone, pwd, superCode, commpanyName, url, new ResponseObserver<HttpBean>() {
            @Override
            public void onSuccess(HttpBean response) {
                dialog.dismiss();
                if (response.getCode() == 200) {
                    startActivity(new Intent(BusinessLicenseCertificationActivity.this, EnterpriseMainActivity.class));
                    BusinessLicenseCertificationActivity.this.finish();
                } else {
                    showToast(response.getMsg());
                }

            }

            @Override
            public void onFail(String message) {
                Log.e("TAG", message);
                dialog.dismiss();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        List<LocalMedia> images = null;
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {// 图片选择结果回调


                images = PictureSelector.obtainMultipleResult(data);
                file = new File(images.get(0).getPath());
                ivBusinessLicense.setImageURI(Uri.fromFile(file));
                tvSendBusinessLicense.setVisibility(View.GONE);
                Log.e("TAG", "imgPath=>>>>" + file.getAbsolutePath());
                //selectList = PictureSelector.obtainMultipleResult(data);

                // 例如 LocalMedia 里面返回三种path
                // 1.media.getPath(); 为原图path
                // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                if (file == null && TextUtils.isEmpty(file.getAbsolutePath())) {
                    showToast("请重新选择图片");
                }

                dialog.show();
                ServiceModel.getServiceModel().setImg(file.getAbsolutePath(), new ResponseObserver<HttpBean>() {
                    @Override
                    public void onSuccess(HttpBean response) {
                        dialog.dismiss();
                        if (response.getCode() == 200) {
                            Log.e("TAG", "上传成功");
                            url = response.getData().toString();
                        } else {
                            showToast("请重新确认图片格式");
                        }
                    }

                    @Override
                    public void onFail(String message) {
                        Log.e("TAG", message);
                        dialog.dismiss();
                    }
                });

            }
        }
    }


    private void initPermission() {
        String[] permissions = new String[]{Manifest.permission.CAMERA,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE};
        //检查权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            // 之前拒绝了权限，但没有点击 不再询问 这个时候让它继续请求权限
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.CAMERA)) {
                Toast.makeText(this, "用户曾拒绝打开相机权限", Toast.LENGTH_SHORT).show();
                ActivityCompat.requestPermissions(this, permissions, REQUEST_PERMISSIONS);
            } else {
                //注册相机权限
                ActivityCompat.requestPermissions(this, permissions, REQUEST_PERMISSIONS);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
//        switch (requestCode) {
//            case REQUEST_PERMISSIONS:
//                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                    //成功
//                    Toast.makeText(this, "用户授权相机权限", Toast.LENGTH_SHORT).show();
//                } else {
//                    // 勾选了不再询问
//                    Toast.makeText(this, "用户拒绝相机权限", Toast.LENGTH_SHORT).show();
//                    /**
//                     * 跳转到 APP 详情的权限设置页
//                     *
//                     * 可根据自己的需求定制对话框，点击某个按钮在执行下面的代码
//                     */
////                    Intent intent = Util.getAppDetailSettingIntent(PhotoFromSysActivity.this);
//                    startActivity(intent);
//                }
//                break;
//        }
    }

}
